import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
// import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
// import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import type { RequestConfig } from 'umi';
import type {
  RequestOptionsInit,
  // RequestInterceptor,
  // ResponseInterceptor,
  ResponseError,
} from 'umi-request';


// const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  // device_select?: API.GreeProductItem;
  device_id?: number;
  device_imsi?:  string;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const resp = await queryCurrentUser();
      return resp.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // 页面水印
    /*     waterMarkProps: {
          content: initialState?.currentUser?.name,
        }, */
    // 每页的角尾页面
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    /*     links: isDev
          ? [
              <Link to="/umi/plugin/openapi" target="_blank">
                <LinkOutlined />
                <span>OpenAPI 文档</span>
              </Link>,
              <Link to="/~docs">
                <BookOutlined />
                <span>业务组件文档</span>
              </Link>,
            ]
          : [], */
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};

/* const headerInfo: RequestInterceptor = (url: string, options: RequestInit) => {
  if (localStorage.getItem('token')) {
    const token = `Bearer ` + localStorage.getItem('token');
    // options.headers.Authorization = `Bearer ` + localStorage.getItem('token');
    options.headers = {
      ...options.headers,
      "Authorization": token,
      'Content-Type': 'application/json',
    }
  }
  console.log("url", url);
  return { url, options };
} */
/**
 * 异常处理程序
 */
const errorHandler = (error: ResponseError) => {
  const { response } = error;
  if (!response) {
    // eslint-disable-next-line no-param-reassign
    error.message = '您的网络发生异常，无法连接服务器'
  };
}

// src/app.ts
const tokenHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  // console.log("-----tokenHeaderInterceptor------")
  if (localStorage.getItem('token')) {
    const token = `${localStorage.getItem('token')}`;
    //  console.log("header token:", token)
    // options.headers.Authorization = `Bearer ` + localStorage.getItem('token');
    options.headers = {
      ...options.headers,
      "Authorization": "greeyjy@web", // 如果没有token,需要访问后端，则不能设为空，需设为："my-Author"
      "token": token,
    }
  } else {
    options.headers = {
      ...options.headers,
      "Authorization": "greeyjy@web", // 如果没有token,需要访问后端，则不能设为空，需设为："my-Author"
    }
  }

  return {
    url: `${url}`,
    options: { ...options, interceptors: true },
  };
};

// src/app.ts
const tokenResponseInterceptors = (response: Response, options: RequestOptionsInit) => {
  // console.log("*******tokenResponseInterceptors*******")
  const token = response.headers.get("token")
  if (token) {
    //  console.log("response token:", token)
    localStorage.setItem("token", token)
  }
  return response;
};


export const request: RequestConfig = {
  errorHandler,
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [tokenHeaderInterceptor],
  responseInterceptors: [tokenResponseInterceptors],

};
